import { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Task, SelectedTaskDisplay,CustomTask } from './types';
import { CustomTaskForm } from '../../components/HomeDashboard/CustomTaskForm';

interface TaskExecutionProps {
  tasksByCategory: { [key: string]: Task[] };
  addTaskToContext?: (task: Omit<Task, 'id' | 'createdAt'>) => Promise<void>;
}

export const TaskExecution = ({ tasksByCategory, addTaskToContext }: TaskExecutionProps) => {
  const navigate = useNavigate();
  const [selectedTasks, setSelectedTasks] = useState<string[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [expandedDropdownCategories, setExpandedDropdownCategories] = useState<string[]>([]);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [keepSelections, setKeepSelections] = useState(false);
  const [activeTab, setActiveTab] = useState<'quick' | 'custom'>('quick');

  // 处理点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 切换下拉框分类的展开/折叠状态
  const toggleDropdownCategory = (category: string, event: React.MouseEvent) => {
    event.stopPropagation();
    setExpandedDropdownCategories(prev => 
      prev.includes(category)
        ? prev.filter(c => c !== category)
        : [...prev, category]
    );
  };

  // 获取过滤后的任务选项（按分类分组）
  const getFilteredTasksByCategory = () => {
    const filteredTasks: { [key: string]: Task[] } = {};
    
    Object.entries(tasksByCategory).forEach(([category, tasks]) => {
      if (!filteredTasks[category]) {
        filteredTasks[category] = [];
      }
      
      // 添加该分类下的符合搜索条件的任务
      tasks.forEach(task => {
        if (!searchQuery || task.taskTitle.toLowerCase().includes(searchQuery.toLowerCase())) {
          filteredTasks[category].push(task);
        }
      });
    });

    // 移除没有符合条件任务的分类
    Object.keys(filteredTasks).forEach(category => {
      if (filteredTasks[category].length === 0) {
        delete filteredTasks[category];
      }
    });

    return filteredTasks;
  };

  // 获取已选任务的显示信息
  const getSelectedTasksDisplay = (): SelectedTaskDisplay[] => {
    return selectedTasks.map(taskId => {
      // 先检查是否是类别选择
      if (taskId.startsWith('category:')) {
        const category = taskId.replace('category:', '');
        return {
          id: taskId,
          taskTitle: `${category} (全部)`
        };
      }
      
      // 否则是单个任务选择
      const task = Object.values(tasksByCategory)
        .flat()
        .find(t => t.id === taskId);
        
      return {
        id: taskId,
        taskTitle: task?.taskTitle || '未知任务'
      };
    });
  };

  // 清除所有选择
  const clearSelections = () => {
    setSelectedTasks([]);
  };

  // 移除单个选择
  const removeSelection = (taskId: string) => {
    setSelectedTasks(prev => prev.filter(id => id !== taskId));
  };

  // 处理任务选择
  const handleTaskSelection = (taskId: string) => {
    // 检查是否是类别选择
    if (taskId.startsWith('category:')) {

      
      // 如果已经选择了其他类别或个别任务，则清空然后选择当前类别
      if (selectedTasks.some(id => id.startsWith('category:') && id !== taskId) || 
          selectedTasks.some(id => !id.startsWith('category:'))) {
        setSelectedTasks([taskId]);
      } else {
        // 否则切换当前类别的选择状态
        setSelectedTasks(prev => prev.includes(taskId) ? [] : [taskId]);
      }
    } else {
      // 如果已经选择了类别，则清空选择
      if (selectedTasks.some(id => id.startsWith('category:'))) {
        setSelectedTasks([taskId]);
      } else {
        // 否则切换当前任务的选择状态，并限制最多选择3个任务
        setSelectedTasks(prev => {
          if (prev.includes(taskId)) {
            return prev.filter(id => id !== taskId);
          } else {
            return prev.length < 3 ? [...prev, taskId] : prev;
          }
        });
      }
    }
  };

  // 处理自定义任务提交
  const handleCustomTaskSubmit = (customTask: CustomTask & { saveToLibrary?: boolean }) => {
    console.log('Custom task submitted:', customTask);
    
    // 如果勾选了保存选项且有保存任务的方法
    if (customTask.saveToLibrary && addTaskToContext) {
      // 保存任务到上下文（不包含临时id，让上下文生成新id）
      addTaskToContext({
        taskTitle: customTask.taskTitle,
        taskGuide: customTask.taskGuide,
        category: customTask.category,
      });
    }

    // 跳转到执行页面，传递完整的任务信息而不仅仅是ID
    navigate('/execution', {
      state: {
        selectedTaskIds: [customTask.id],
        customTasks: [customTask], // 传递完整的自定义任务
        fromPage: '首页'
      }
    });
  };

  // 处理执行任务按钮点击
  const handleExecuteTask = () => {
    if (selectedTasks.length === 0) return;
    
    // 收集要执行的任务ID
    let taskIdsToExecute: string[] = [];  
    
    // 处理类别选择
    selectedTasks.forEach(selection => {
      if (selection.startsWith('category:')) {
        const category = selection.replace('category:', '');
        const categoryTasks = tasksByCategory[category] || [];
        taskIdsToExecute = taskIdsToExecute.concat(categoryTasks.map(task => task.id));
      } else {
        // 直接添加单个任务ID
        taskIdsToExecute.push(selection);
      }
    });
    
    // 导航到TaskExecution页面，并通过state传递选定的任务ID
    navigate('/execution', { 
      state: { 
        selectedTaskIds: taskIdsToExecute,
        fromPage: '首页'
      } 
    });
    
    // 如果不保留选择，则清空
    if (!keepSelections) {
      clearSelections();
    }
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm mb-8">
      <div className="p-6">
        <h2 className="text-xl font-semibold mb-6 flex items-center dark:text-white">
          <span className="mr-2">▶</span>
          任务执行
        </h2>
        
        <div className="space-y-6">
          <div className="border-b dark:border-gray-700">
            <div className="flex gap-4">
              <button
                className={`px-4 py-2 ${
                  activeTab === 'quick'
                    ? 'text-blue-500 border-b-2 border-blue-500'
                    : 'text-gray-500 dark:text-gray-400'
                }`}
                onClick={() => setActiveTab('quick')}
              >
                快速执行
              </button>
              <button
                className={`px-4 py-2 ${
                  activeTab === 'custom'
                    ? 'text-blue-500 border-b-2 border-blue-500'
                    : 'text-gray-500 dark:text-gray-400'
                }`}
                onClick={() => setActiveTab('custom')}
              >
                自定义任务
              </button>
            </div>
          </div>

          {activeTab === 'quick' ? (
            <div className="space-y-4">
              <div className="relative">
                <h3 className="text-sm font-medium mb-2 dark:text-gray-300">选择要执行的任务</h3>
                
                {/* 已选任务标签显示 */}
                {selectedTasks.length > 0 && (
                  <div className="flex flex-wrap gap-2 mb-2">
                    <div className="flex items-center text-sm text-gray-600 dark:text-gray-400">
                      {selectedTasks.length} selected:
                    </div>
                    {getSelectedTasksDisplay().map(task => (
                      <div
                        key={task.id}
                        className="flex items-center gap-1 px-2 py-1 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-md text-sm"
                      >
                        {task.taskTitle}
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            removeSelection(task.id);
                          }}
                          className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-200"
                        >
                          ×
                        </button>
                      </div>
                    ))}
                    <button
                      onClick={clearSelections}
                      className="text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                    >
                      Clear
                    </button>
                  </div>
                )}

                {/* 搜索框和下拉触发器 */}
                <div className="relative" ref={dropdownRef}>
                  <div
                    className="w-full p-2 border rounded-md flex items-center gap-2 cursor-pointer dark:bg-gray-700 dark:border-gray-600"
                    onClick={() => setIsDropdownOpen(prev => !prev)}
                  >
                    {selectedTasks.length > 0 ? (
                      <div className="flex flex-1 flex-wrap gap-2">
                        {getSelectedTasksDisplay().map(task => (
                          <div
                            key={task.id}
                            className="flex items-center gap-1 px-2 py-1 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-md text-sm"
                            onClick={(e) => e.stopPropagation()}
                          >
                            {task.taskTitle}
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                removeSelection(task.id);
                              }}
                              className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-200"
                            >
                              ×
                            </button>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <span className="flex-1 text-gray-400">选择任务...</span>
                    )}
                    <button
                      className={`text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transform transition-transform duration-200 ${
                        isDropdownOpen ? 'rotate-180' : ''
                      }`}
                      onClick={(e) => {
                        e.stopPropagation();
                        setIsDropdownOpen(prev => !prev);
                      }}
                    >
                      ▼
                    </button>
                  </div>

                  {/* 下拉选项列表 */}
                  {isDropdownOpen && (
                    <div className="absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-md shadow-lg max-h-[400px] overflow-hidden">
                      {/* 搜索框 */}
                      <div className="sticky top-0 p-2 bg-white dark:bg-gray-800 border-b dark:border-gray-700">
                        <div className="relative">
                          <input
                            type="text"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            placeholder="搜索任务..."
                            className="w-full pl-8 pr-2 py-1.5 border rounded-md outline-none dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
                            onClick={(e) => e.stopPropagation()}
                          />
                          <span className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-400">
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                          </span>
                        </div>
                      </div>

                      {/* 选项列表 */}
                      <div className="overflow-auto max-h-[320px]">
                        {Object.entries(getFilteredTasksByCategory()).map(([category, tasks]) => (
                          tasks.length > 0 && (
                            <div key={category} className="border-b last:border-b-0 dark:border-gray-700">
                              <label
                                className="flex items-center gap-2 px-4 py-2 bg-gray-50 dark:bg-gray-700 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600"
                              >
                                <input
                                  type="checkbox"
                                  checked={selectedTasks.includes(`category:${category}`)}
                                  onChange={() => handleTaskSelection(`category:${category}`)}
                                  className="rounded text-blue-500 dark:bg-gray-700"
                                />
                                <div className="flex items-center gap-2 flex-1">
                                  <span className="text-gray-700 dark:text-gray-200 font-medium">{category}</span>
                                  <span className="text-sm text-gray-500 dark:text-gray-400">({tasks.length})</span>
                                </div>
                                <button
                                  onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    toggleDropdownCategory(category, e);
                                  }}
                                  className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
                                >
                                  <span className={`transform transition-transform duration-200 inline-block ${
                                    expandedDropdownCategories.includes(category) ? 'rotate-180' : ''
                                  }`}>
                                    ▼
                                  </span>
                                </button>
                              </label>
                              
                              <div className={`transition-all duration-200 ${
                                expandedDropdownCategories.includes(category)
                                  ? 'max-h-[1000px] opacity-100'
                                  : 'max-h-0 opacity-0'
                              } overflow-hidden`}>
                                <div className="bg-white dark:bg-gray-800 pl-8">
                                  {tasks.map(task => (
                                    <label
                                      key={task.id}
                                      className="flex items-center gap-2 px-4 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
                                    >
                                      <input
                                        type="checkbox"
                                        checked={selectedTasks.includes(task.id) || selectedTasks.includes(`category:${category}`)}
                                        onChange={() => handleTaskSelection(task.id)}
                                        disabled={selectedTasks.includes(`category:${category}`)}
                                        className="rounded text-blue-500 dark:bg-gray-700 disabled:opacity-50"
                                      />
                                      <span className={`dark:text-gray-200 ${selectedTasks.includes(`category:${category}`) ? 'opacity-50' : ''}`}>
                                        {task.taskTitle}
                                      </span>
                                    </label>
                                  ))}
                                </div>
                              </div>
                            </div>
                          )
                        ))}
                        
                        {Object.entries(getFilteredTasksByCategory()).length === 0 && (
                          <div className="px-4 py-3 text-center text-gray-500 dark:text-gray-400">
                            没有找到匹配的任务
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
                
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-2">
                  可以选择一个类别或最多三个单独的任务。
                </p>
              </div>

              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={keepSelections}
                  onChange={(e) => setKeepSelections(e.target.checked)}
                  className="rounded text-blue-500 dark:bg-gray-700 dark:border-gray-600"
                />
                <span className="text-sm dark:text-gray-300">执行后保留选择</span>
              </label>

              <button 
                className="bg-blue-500 text-white px-6 py-2 rounded-md flex items-center gap-2 hover:bg-blue-600"
                onClick={handleExecuteTask}
                disabled={selectedTasks.length === 0}
              >
                <span>▶</span>
                执行 {selectedTasks.length} 个任务
              </button>
            </div>
          ) : (
            <CustomTaskForm 
              onSubmit={handleCustomTaskSubmit} 
              categories={Object.keys(tasksByCategory)}
            />
          )}
        </div>
      </div>
    </div>
  );
}; 

export default TaskExecution